/**
 * 根据 parentId 递归生成 省市区 嵌套格式
 * @param regions 数据
 * @param parentId 父级id
 * @param cache
 * @returns 返回省市区 嵌套格式数据
 */
export function buildRegionTree(
  regions: any,
  parentId: string | null = null,
  cache: Set<string> = new Set(),
) {
  try {
    const filteredRegions = regions.filter(
      (region: any) => region.parentId === parentId,
    );

    return filteredRegions.map((region: any) => {
      if (cache.has(region.code)) {
        return {
          name: region.name,
          code: region.code,
        };
      }
      cache.add(region.code);
      const children = buildRegionTree(regions, region.code, cache);

      return {
        name: region.name,
        code: region.code,
        children: children.length > 0 ? children : undefined,
      };
    });
  } catch (error) {
    console.error('生成省市区数据失败', error);
    return [];
  }
}
